﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Wiwi.Models;
using Wiwi.ViewModels;
using System.Web.Security;

using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace Wiwi.Controllers
{
    public class WantKeywordController : ApplicationController
    {
        //
        // GET: /WantKeyword/

        public ActionResult Index()
        {
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult AddkeyWord(string kw)
        {
            WiwiEntities1 db = new WiwiEntities1();
            var kwe = from kw1 in db.A_KeyWord where kw1.keyword.ToUpper()== kw.Trim().ToUpper() select kw1;
            if (kwe.Any())
            {
                return RedirectToAction("../Home/Index/");
            }
            A_KeyWord kwn = new A_KeyWord();
            kwn.KeywordID = Guid.NewGuid();
            kwn.keyword = kw.Trim();
            db.AddToA_KeyWord(kwn);
            db.SaveChanges();
            return RedirectToAction("../Home/Index/");
        }
        [Authorize]
        [HttpPost]
        public ActionResult SaveWiwi()
        {
            if (Request.Form["tags-ajax"] != null)
            {
                WiwiEntities1 db = new WiwiEntities1();
                MembershipUser usr = Membership.GetUser();
                Guid gusr = new Guid(usr.ProviderUserKey.ToString());
                A_Want wn = new A_Want();
                wn.WantID = Guid.NewGuid();
                wn.WantDesc = Request.Form["tags-ajax"].ToString();
                db.AddToA_Want(wn);
                A_Want_Wanter us = new A_Want_Wanter();
                us.Want_Wanter_RelID = Guid.NewGuid();
                us.IsCurrentOwner = true;
                us.WantID = wn.WantID;
                us.UserID = gusr;
                us.IsClosed = false;
                us.IsCreator = true;
                us.ExpiryDate=DateTime.Now.AddDays(7);
                us.WiwiDate = DateTime.Now;
                db.AddToA_Want_Wanter(us);
                db.SaveChanges();
                string[] str = Request.Form["hidKeyWord"].ToString().Split('?');
                foreach (string st in str)
                {
                    if (st != "")
                    {
                        var k = (from kk in db.A_KeyWord where kk.keyword == st select kk).Take(1);
                        if (k.Any())
                        {
                            A_WantKeyword kw = new A_WantKeyword();
                            kw.WantID = wn.WantID;
                            foreach(var k1 in k)
                            {
                                kw.KeyWordID = k1.KeywordID;
                            }
                            db.AddToA_WantKeyword(kw);
                            db.SaveChanges();
                        }
                    }
                }
                //ServiceReference1.Service1Client cli = new ServiceReference1.Service1Client();
                //cli.SendNotificationCompleted += new EventHandler<ServiceReference1.SendNotificationCompletedEventArgs>(cli_SendNotificationCompleted);
                //cli.SendNotificationAsync(wn.WantID);
            }
            return RedirectToAction("../Home/Profile/");
        }

        private void cli_SendNotificationCompleted(object sender, ServiceReference1.SendNotificationCompletedEventArgs args)
        {
            string str = args.Result.ToString();
        }
        [HttpPost]
        public ActionResult MyAccount()
        {
            myAccountList mod = PrepareMyAccount(null);
            return View(mod);
        }
        [HttpPost]
        [Authorize]
        public ActionResult ExportGrid()
        {
            if (Request.Form["HidExportval"] != null)
            {
                myAccountList mod = PrepareMyAccount(Request.Form["HidExportval"].ToString());
                var grid = new System.Web.UI.WebControls.GridView();
                grid.DataSource = mod.acc;
                grid.DataBind();
                Response.ClearContent();
                Response.AddHeader("content-disposition", "attachment; filename=ExportGrid.xls");
                Response.ContentType = "application/excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                grid.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.End();
                return View(mod);
            }
            return View();
        }
        [Authorize]
        public ActionResult MyAccount(string interval)
        {
            myAccountList mod = PrepareMyAccount(interval);
            return View(mod);
        }
        [Authorize]
        public myAccountList PrepareMyAccount(string interval)
        {
            WiwiEntities1 db = new WiwiEntities1();
            DateTime Lastdate;
            if (Request.Form["interval"] == null) Lastdate = DateTime.Today.Date.AddHours(-24);
            else Lastdate = DateTime.Now.AddHours(-double.Parse(Request.Form["interval"].ToString()));
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            myAccountList mod = new myAccountList();
            List<myAccount> acclst = new List<myAccount>();
            var purc = (from pr in db.A_UserCredit where pr.UserID == gusr && pr.DatePurchased >= Lastdate select pr).ToList();
            var cons = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr && cn.DateConsumed >= Lastdate select cn).ToList();
            //var jin = from pc in purc select pc.DatePurchased 
            foreach (var pc in purc)
            {
                myAccount acc = new myAccount();
                acc.Transactiondate = pc.DatePurchased;
                acc.Purchase = pc.CreditPurchased;
                acc.Description = "Credit purchased";
                acclst.Add(acc);
            }
            foreach (var cn in cons)
            {
                myAccount acc = new myAccount();
                acc.Transactiondate = cn.DateConsumed;
                acc.consumption = cn.CreditConsumed;
                acc.Description = "Credit consumed";
                acclst.Add(acc);
            }

            var Nlist = (from ac in acclst orderby ac.Transactiondate select ac).ToList();
            mod.acc = Nlist;
            mod.bal = 0;
            var recs = (from pr in db.A_UserCredit where pr.UserID == gusr select pr).Take(1);
            if (recs.Count() > 0)
            {
                var pur = (from pr in db.A_UserCredit where pr.UserID == gusr select pr.CreditPurchased).Sum();
                mod.bal = pur;
            }
            var recs1 = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Take(1);
            if (recs1.Count() > 0)
            {
                var cns = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Sum();
                mod.bal = mod.bal -cns;
            }
            return mod;
        }
        [Authorize]
        public ActionResult BuyCredit(string selval)
        {
            int bal = 0;
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            var recs = (from pr in db.A_UserCredit where pr.UserID == gusr select pr).Take(1);
            if (recs.Count() > 0)
            {
                var pur = (from pr in db.A_UserCredit where pr.UserID == gusr select pr.CreditPurchased).Sum();
                bal = pur;
            }
            var recs1 = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Take(1);
            if (recs1.Count() > 0)
            {
                var cns = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Sum();
                bal = bal - cns;
            }
            return View(bal);
        }
        [Authorize]
        [HttpPost]
        public ActionResult BuyCredit()
        {
            int bal = 0;
            WiwiEntities1 db = new WiwiEntities1();
            MembershipUser usr = Membership.GetUser();
            Guid gusr = new Guid(usr.ProviderUserKey.ToString());
            if (Request.Form["raioCredit"] != null)
            {
                string str = Request.Form["raioCredit"].ToString();
                A_UserCredit cr = new A_UserCredit();
                cr.UserID = gusr;
                cr.Amount = int.Parse(str) / 2;
                cr.CreditPurchased = int.Parse(str);
                cr.DatePurchased = DateTime.Now;
                db.AddToA_UserCredit(cr);
                db.SaveChanges();
            }
            var recs = (from pr in db.A_UserCredit where pr.UserID == gusr select pr).Take(1);
            if (recs.Count() > 0)
            {
                var pur = (from pr in db.A_UserCredit where pr.UserID == gusr select pr.CreditPurchased).Sum();
                bal = pur;
            }
            var recs1 = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Take(1);
            if (recs1.Count() > 0)
            {
                var cns = (from cn in db.A_UserCreditConsumed where cn.UserID == gusr select cn.CreditConsumed).Sum();
                bal = bal - cns;
            }
            return View(bal);
        }
    }
}
